#coding:utf-8
import time
from utils.kafka_handler import SysProducerHandler
import os
import redis
import hashlib
import json

HOST = 'rm32275.hebe.grid.sina.com.cn'
PORT = 32275

class FpTool():
    def __init__(self, logger='',write_log_to_kafka=False):
        self.log = logger
        self.write_log_to_kafka = write_log_to_kafka
        self.log_producer = SysProducerHandler(topic="groupid_log", hosts=["10.13.40.138:9092"],username=None,password=None)
        self.group_id_cache = redis.StrictRedis(host=HOST, port=PORT, db=2)  ## group_id指纹缓存 解决并发指纹不一致问题
        ## 热榜query
        w_host = 'rm11930.eos.grid.sina.com.cn'
        w_port = '11930'
        w_db = 15
        self.hot_redis_client = redis.StrictRedis(host=w_host,port=w_port,db=w_db)

    def logger(self, text):
        try:
            text = "GROUP_ID_LOG - {} - {} - {} - {}".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), os.getppid(), os.getpid(), text)
            if self.write_log_to_kafka:
                try:
                    self.log_producer.write(text.encode('utf-8'))
                except Exception as e:
                    text += "TO KAFKA ERROR:{}".format(e)
            if self.log:    self.log.info(text)
            if not self.log:    print(text)
        except Exception as e:
            print(e)

    def get_md5(self, title):
        '''返回title的md5'''
        md5 = hashlib.md5(title.encode('utf-8')).hexdigest()
        return md5

    def cost(func):
        def wrapper(self, *args, **kwargs):
            start_time = time.time()
            res = func(self, *args, **kwargs)
            end_time = time.time()
            total_cost = (end_time - start_time)*1000
            self.logger('@@@@@@@ {} costs {:.4f}ms'.format(func.__name__, total_cost))
            return res
        return wrapper

    def hit_cache(self, title):
        try:
            _key = "gid_{}".format(self.get_md5(title))
            ret = self.group_id_cache.get(_key)
            if not ret:	return {}
            return json.loads(ret)
        except Exception as e:
            print(e)
        return {}
                
    def set_cache(self, title, data, ex=3600*12):
        try:
            _key = "gid_{}".format(self.get_md5(title))
            return self.group_id_cache.set(_key, json.dumps(data), ex=ex) 
        except Exception as e:
            print(e)
        return False

    def function_score(self, delta, ratio=0.15):
        ''' 时间衰减函数 '''
        #return max(1 / ( 1 + ratio*delta*delta ), 0.4)
        return max(1 / ( 1 + ratio*delta ), 0.25)
    
    def jaccard_with_weights(self, title_split, query_weights, cand_title_split, cand_weights):
        title_split      = title_split.split()
        cand_title_split = cand_title_split.split()
        token_weights=dict(dict(zip(title_split, query_weights)), **dict(zip(cand_title_split, cand_weights)))

        tokens_q = set(title_split)
        tokens_t = set(cand_title_split)

        inter = tokens_q & tokens_t
        union = tokens_q | tokens_t

        if not inter:   return 0.0
        # tqr&ctr
        '''
        top_score = sum([token_weights[tk] for tk in inter])
        q_score = sum([token_weights[tk] for tk in tokens_q])
        t_score = sum([token_weights[tk] for tk in tokens_t])

        score = (top_score/q_score)*(top_score/t_score)
        '''
        score = sum([token_weights[tk] for tk in inter])/sum([token_weights[tk] for tk in union])

        return score

    def jaccard_distance(self, list_1, list_2):
        '''计算两个list的jaccard距离'''

        if not any(list_1) or not any(list_2): return 0.0

        set_1 = set(list_1)
        set_2 = set(list_2)

        inter = float(len(set_1 & set_2))
        union = float(len(set_1 | set_2))

        return inter/union

    def find_lcsubstr(self, s1, s2):
        m=[[0 for i in range(len(s2)+1)]  for j in range(len(s1)+1)]
        mmax, p = 0, 0
        for i in range(len(s1)):
            for j in range(len(s2)):
                if s1[i]==s2[j]:
                    m[i+1][j+1]=m[i][j]+1
                    if m[i+1][j+1]>mmax:
                        mmax=m[i+1][j+1]
                        p=i+1
        return s1[p-mmax:p],mmax

    def all_lcsubstr(self, s1, s2):
        result = []
        while True:
            ret = self.find_lcsubstr(s1, s2)
            if ret[1] == 0 or len(ret[0].strip()) < 2: break
            result.append(ret[0])
            s1 = s1.replace(ret[0],'')
            s2 = s2.replace(ret[0],'')
        return result

    def is_chinese(self, text):
        if not text:	return False
        for ch in text:
            if u'\u4e00' <= ch <= u'\u9fff':
                return True
        return False
